import { createRouter, createWebHashHistory } from 'vue-router';
import { firstMenu, mapMenusToRoutes } from '@/utils/map.menus';

import type { RouteRecordRaw } from 'vue-router';
import localCache from '@/utils/cache';
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/404/404.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue')
    // 动态路由的操作开始
    // children: [] => 在vuex中的login里面进行动态配置
  }
];

const router = createRouter({
  routes,
  history: createWebHashHistory()
});

router.beforeEach((to) => {
  if (to.path !== '/login') {
    const token = localCache.getCache('token');
    if (!token) {
      return '/login';
    }
  }

  if (to.path == '/main') {
    return firstMenu.url;
  }
});

// console.log(localCache.getCache('userMenus'));
export function dynamicRouter() {
  const dynamicRoutes = mapMenusToRoutes(localCache.getCache('userMenus'));
  dynamicRoutes.forEach((route) => {
    router.addRoute('main', route);
  });
}

export default router;
